/**
 * @program: LeetCode
 * @description: LeetCode :  剑指 Offer II 034. 外星语言是否排序
 * @author: WXY
 * @create: 2022-12-28 15:29
 * @Version 1.0
 **/


public class offer_eleven2_isAlienSorted {
    public static boolean isAlienSorted(String[] words, String order) {
        char[] ch = order.toCharArray();
        int[] arr = new int[26];
        for (int i = 0; i < ch.length; i++) {
            arr[ch[i] - 'a'] =   i;
        }
        for (int i = 0; i < words.length - 1; i++) {
            if (!check(words[i], words[i + 1],arr)) {
                return false;
            }
        }
        return true;
    }

    private static boolean check(String wordA, String wordB, int[] arr) {
        char[] strA = wordA.toCharArray();
        char[] strB = wordB.toCharArray();
        int lenA = strA.length, i = 0;
        int lenB = strB.length, j = 0;
        while (i < lenA && j < lenB) {
            int indexA = arr[strA[i++] - 'a'];
            int indexB = arr[strB[j++] - 'a'];
            if (indexA > indexB) {
                return false;
            } else if (indexA < indexB) {
                return true;
            }
        }
        if (i < lenA) return false;
        if (j < lenB) return true;
        return true;
    }


}
